package com.lgq.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lgq.bean.Message;
import com.lgq.bean.Student;
import com.lgq.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: stu_info_manager
 * @description:
 * @author: Lin
 * @create: 2019-01-05 00:08
 **/
@Controller
public class StudentController {

    @Autowired
    StudentService studentService;

/**
 * 获取学生信息的Json数据
 */
    @ResponseBody
    @RequestMapping("/stus")
    public Message getStudentWithJson(@RequestParam(value = "pn",defaultValue = "1") Integer pn){

        //分页插件PageHelper,设置每页五个数据
        PageHelper.startPage(pn,5);

        //调用Service的获取全部
        List<Student> students=studentService.getAll();

        //传入数据，传入连续显示的页数
        PageInfo pageInfo=new PageInfo(students,5);

        return Message.success().add("pageInfo",pageInfo);
    }


    /**
     * 保存
     * @param student
     * @param result
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/stu",method = RequestMethod.POST)
    public Message saveStudent(@Valid Student student, BindingResult result){
        if (result.hasErrors()){
            //放入错误信息的map
            Map<String,Object> map=new HashMap<String,Object>();
            //获取错误字段
            List<FieldError> errors=result.getFieldErrors();
            for (FieldError fieldError :errors) {
                System.out.println("错误字段名："+fieldError.getField());
                System.out.println("错误信息："+fieldError.getDefaultMessage());
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            //返回前端带有错误字段的Json数据
            return Message.fail().add("errorField",map);
        }
        studentService.saveStudent(student);
        return Message.success();
    }


    /**
     * 校验学生姓名
     * @param stuName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkUser",method = RequestMethod.POST)
    public Message check(@RequestParam("stuName") String stuName){
        String regx = "(^[\u2E80-\u9FFF]{2,4})";
        if(!stuName.matches(regx)){
            return Message.fail().add("va_msg", "姓名只能是2-4位中文");
        }else{
            return Message.success();
        }
    }


    /**
     * 获取指定ID的学生数据
     * @param id
     * @return
     */
    @RequestMapping(value="/stu/{id}",method=RequestMethod.GET)
    @ResponseBody
    public Message getStu(@PathVariable("id")Integer id){

        Student student = studentService.getStu(id);
        return Message.success().add("student", student);
    }


    /**
     * 更新学生数据
     * @param student
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/stu/{stuId}",method = RequestMethod.PUT)
    public Message saveStu(Student student, HttpServletRequest request){
        studentService.updateStudent(student);
        return Message.success();
    }


    /**
     * 删除学生通过字符串解析成Integer
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/stu/{ids}",method = RequestMethod.DELETE)
    public Message deleteStudentById(@PathVariable String ids){
        if (ids.contains("-")){
            List<Integer> deleteList=new ArrayList<>();
            String[] deleteString=ids.split("-");
            for (String str:deleteString) {
                Integer id=Integer.parseInt(str);
                deleteList.add(id);
            }
            studentService.deleteBatch(deleteList);
        }else{
            Integer id=Integer.parseInt(ids);
            studentService.deleteStudentById(id);
        }
        return Message.success();

    }
}
